/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ContentManagers.Servlets;

import ContentManagers.Models.Customer;
import ContentManagers.RoleManagers.CustomerManager;
import ContentManagers.Security.Hasher;
import ContentManagers.Security.Validator;
import ContentManagers.Security.WebLogger;
import java.io.IOException;
import java.io.PrintWriter;
import java.security.NoSuchAlgorithmException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Martin San Diego
 */
public class ServletCustomerPasswordReset extends HttpServlet {

    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try {   
                HttpSession session = request.getSession();
                boolean checker = false;
            
                Customer resetPassCustomer = new Customer();
                String tempPassword[] = new String[2];
                
                Integer count = (Integer)session.getAttribute("count");
                // If COUNT is not found, create it and add it to the session
                if ( count == null ) {
                    count = new Integer(0);
                    session.setAttribute("count", count);
                }
                
                if(session.getAttribute("username").equals(request.getParameter("username")) == true && ((Integer)session.getAttribute("count")) <3 )
                {   //check if user inputed correct username corresponding with current session variable   

                    resetPassCustomer.setUsername(Validator.inputSanitizer(request.getParameter("username")));
                    resetPassCustomer.setPassword(Validator.passwordSanitizer(request.getParameter("oldPassword")));
                    
                    checker = new CustomerManager().checkCustomer(resetPassCustomer);
                    //check if oldPassword input is correct
                    
                    if (checker == true && (request.getParameter("newPassword").equals(request.getParameter("newPassword2")) == true)) 
                    {   //proceed to changing password if inputs are correct
                         
                        tempPassword = Hasher.processPassword(Validator.passwordSanitizer(request.getParameter("newPassword")));
                        resetPassCustomer.setPassword(tempPassword[0]);
                        resetPassCustomer.setPasswordSalt(tempPassword[1]);
            
                        checker = new CustomerManager().resetPassword(resetPassCustomer);
                        
                        if(checker == true)
                        {
                            WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Customer "+session.getAttribute("username")+" password reset successful.",true);
                            session.setAttribute("message", "1");
                            response.sendRedirect("user_account.jsp"); //update successful
                        }
                        else
                        {
                            WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Customer "+session.getAttribute("username")+" password reset failed.",false);
                            session.setAttribute("message", "0");
                            response.sendRedirect("user_account.jsp"); //update failed
                        }
                    }
                    else if ((Integer)session.getAttribute("count")>=2) {
                    WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Password reset failed attempts exceeded 3 for Username: "+session.getAttribute("username")+"",false);
                    session.setAttribute("message", "0");
                    response.sendRedirect("ServletLogout");         
                    }
                    else
                    {
                        count++;
                        session.setAttribute("count", count);
                        session.setAttribute("message", "0");
                        response.sendRedirect("user_account.jsp");
                        //return to page if inputs are incorrect   
                    }
                }
                else if ((Integer)session.getAttribute("count")>=2) {
                    WebLogger.insertLog(request.getRemoteAddr().toString(),request.getHeader("referer"),request.getRequestURI().toString(),"Password reset failed attempts exceeded 3 for Username: "+session.getAttribute("username")+"",false);
                    response.sendRedirect("ServletLogout");         
                }
                else
                {
                    session.setAttribute("message", "0");
                    count++;
                    session.setAttribute("count", count);
                    response.sendRedirect("user_account.jsp");
                    //return to page if inputs are incorrect   
                }
                
            
        } finally {            
            out.close();
        }
    }
    
    
    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /**
     * Handles the HTTP
     * <code>GET</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Handles the HTTP
     * <code>POST</code> method.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    /**
     * Returns a short description of the servlet.
     *
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
